package com.myblockchain.utility;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liu
 */
public class RSACoder {
    public static final String KEY_ALGORITHM ="RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    /**
     * @param data 是要加密的数据
     * @param privateKey 是发送方的私钥，为了方便代码运行，我们都用一个String
     * 来存放，其实java内部需要转换成对应类的对象才能进行计算。
     */
    public static String sign(byte[] data, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException, SignatureException {
//        解密base64编码的私钥
        byte[] key = decryptBASE64(privateKey);
//        构造PKCS8EncodeKeySpec对象
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);

//        KEY_ALGORITHM指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//        取私钥对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);

        return encryptBASE64(signature.sign());
    }

    /**
     * @param data 是要加密的数据
     * @param publicKey 是接收方的公钥，为了方便代码运行，我们都用一个String
     * 来存放，其实java内部需要转换成对应类的对象才能进行计算。
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, IOException {
//        对公钥解密
        byte[] key = decryptBASE64(publicKey);
//        获得公钥的对象
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key pubKey = keyFactory.generatePublic(x509EncodedKeySpec);
//        对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE,pubKey);
        return cipher.doFinal(data);
    }
    /**
     * @param data 是要加密的数据
     * @param privateKey 是接收方的私钥，为了方便代码运行，我们都用一个String
     * 来存放，其实java内部需要转换成对应类的对象才能进行计算。
     */
    public static byte[] decryptByPrivateKey(byte[] data,String privateKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//        对密钥解密
        byte[] keyBytes = decryptBASE64(privateKey);
//        取得私钥的对象
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//        对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE,priKey);

        return cipher.doFinal(data);
    }




    public static String getPublicKey (Map<String, Object> keyMap){
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    public static String getPrivateKey (Map<String, Object> keyMap){
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    private static String encryptBASE64(byte[] encoded) {
        return (new BASE64Encoder()).encodeBuffer(encoded);
    }

    private static byte[] decryptBASE64(String publicKey) throws IOException {
        return (new BASE64Decoder()).decodeBuffer(publicKey);
    }

    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//        公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//        私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY,publicKey);
        keyMap.put(PRIVATE_KEY,privateKey);
        return keyMap;
    }

    /**
     * @param data 是要验证的数据
     * @param pubKey 是发送方的公钥，为了方便代码运行，我们都用一个String
     * 来存放，其实java内部需要转换成对应类的对象才能进行计算。
     * @param sign 签名的内容
     */
    public static boolean verify(byte[] data, String pubKey, String sign) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        byte[] keyBytes = decryptBASE64(pubKey);

//        还原公钥对象
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//        初始化签名对象
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(decryptBASE64(sign));
    }
}
